package com.jinglu.cloud.common.generator;

import com.jinglu.cloud.common.model.entity.BaseEntity;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.jinglu.cloud.common.controller.BaseController;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author lvzhenzhao
 * @date 2021-08-24 3:20 下午
 */
public class CommonGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 生成
     * @param modulePath
     * @param apiModulePath
     * @param author
     * @param dblUrl
     * @param dbUserName
     * @param dbPassword
     * @param packageName
     */
    public static void generator(String modulePath, String apiModulePath, String author, String dblUrl, String dbUserName, String dbPassword, String packageName) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String propertyPath = System.getProperty("user.dir");
        String projectPath = propertyPath + "/" + modulePath;
        String apiPath = propertyPath + "/" + apiModulePath;
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(author);
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(dblUrl);
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(dbUserName);
        dsc.setPassword(dbPassword);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("domain模块名"));
        pc.setParent(packageName);
        String parentPath = pc.getParent().replaceAll("\\.","/");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 自定义输出配置
        List<FileOutConfig> focList = customTemplateConfig(projectPath, parentPath, apiPath, pc);
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setEntity(null);
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        StrategyConfig strategy = createStrategy(pc);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     * 自定义模板输出
     * @param projectPath
     * @param parentPath
     * @param apiPath
     * @param pc
     */
    private static List<FileOutConfig> customTemplateConfig(String projectPath, String parentPath, String apiPath, PackageConfig pc) {
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/java/" + parentPath + "/mapper/mapping/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        String entityTemplatePath = "/templates/entity.java.ftl";
        String apiDomainPath = apiPath + "/src/main/java/" + parentPath + "/" + pc.getEntity() + "/";
        focList.add(new FileOutConfig(entityTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                tableInfo.getImportPackages();
                return apiDomainPath + tableInfo.getEntityName() + StringPool.DOT_JAVA;
            }
        });
        return focList;
    }

    /**
     * 策略配置
     * @param pc
     * @return
     */
    private static StrategyConfig createStrategy(PackageConfig pc) {
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(BaseEntity.class);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass(BaseController.class);
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id", "create_time", "update_time");
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(false);
        String prefix = scanner("表前缀过滤字符(不包含下划线)");
        if (StringUtils.isNotBlank(prefix)) {
            strategy.setTablePrefix(prefix + "_");
        } else {
            strategy.setTablePrefix(pc.getModuleName() + "_");
        }
        return strategy;
    }
}
